/* $Id: mod_perl.c,v 1.1 2006/03/19 20:13:52 jfb Exp $ */
/*
 * Copyright (c) 2003 Jean-Francois Brousseau <jfb@fugusec.net>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#define __CANOPY_MODULE__ 1

#include <sys/types.h>

#include <ctype.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>

#include <EXTERN.h>
#include <perl.h>

#include <canopy/log.h>

#include <httpd/httpd.h>
#include <httpd/module.h>

#include "mod_perl.h"


/* the Perl interpreter */
PerlInterpreter *my_perl = NULL;



/*
 * mod_perl_init()
 *
 * Allocate a new Perl interpreter and prepare it to parse Perl scripts.
 *
 */

int
mod_perl_init(void)
{
	int ret;

	httpd_log(CNP_LOG_INFO, "mod_perl initializing");

	my_perl = perl_alloc();
	if (my_perl == NULL) {
		httpd_log(CNP_LOG_ERR, "failed to allocate Perl interpreter");
		return (-1);
	}

	PL_perl_destruct_level = 1;

	perl_construct(my_perl);

	if (mod_perl_modinit() < 0) {
		return (-1);
	}

	httpd_log(CNP_LOG_NOTICE, "we get here!");

	if (mod_perl_readconf() < 0) {
		return (-1);
	}
	httpd_log(CNP_LOG_NOTICE, "and here!");

	if (mod_perl_startup() < 0) {
		return (-1);
	}

	/* now that we are done intializing, load the Perl modules */
	if (perlmod_loadall() < 0) {
		return (-1);
	}

	return (0);
}


/*
 * mod_perl_cleanup()
 *
 *
 */

void
mod_perl_cleanup(void)
{
	perlmod_unloadall();

	if (my_perl != NULL) {
		perl_destruct(my_perl);
		perl_free(my_perl);
	}
}
